package cn.edu.zjgsu.controller;

import cn.edu.zjgsu.model.Novel;
import cn.edu.zjgsu.service.NovelService;
import cn.edu.zjgsu.template.ResultBean;
import cn.edu.zjgsu.template.ResultPageBean;
import cn.edu.zjgsu.vo.NovelInput;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: wqmei
 * DateTime: 2017/11/10 11:14
 * Description:
 */
@RestController
public class NovelController
{
    @Autowired
    NovelService novelService;


    /**
     * 查询小说列表
     * @return
     */
    @GetMapping("novel")
    public ResultPageBean<Novel> getNovelList()
    {
        ResultPageBean result = new ResultPageBean();
        List<Novel> novelList = novelService.getNoverlList();
        result.setData(novelList);
        return result;
    }

    /**
     * 查询小说详情
     * @param novelId
     * @return
     */
    @GetMapping("novel/{novelId}")
    public ResultBean<Novel> getNovelById(@PathVariable int novelId)
    {
        ResultBean result = new ResultBean();
        Novel novel = novelService.getNoverlById(novelId);
        if(!novel.getCategory().equals("free"))
        {
            /**
             * 检查是否登录(默认登录是付费用户,可以观看付费小说)
             */
            Subject subject = SecurityUtils.getSubject();
            boolean isAuthenticated = subject.isAuthenticated();
            if(isAuthenticated==false)
            {
                result.setCode(401);
                return result;
            }
        }

        result.setData(novel);
        return result;
    }

    @PostMapping("novel")
    public ResultBean addNovel(@RequestBody NovelInput novelInput)
    {
        ResultBean result = new ResultBean();
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isPermitted("novel:add"))
        {
            result.setCode(401);
            return result;
        }
        Novel novel = novelInput.convert();
        novelService.addNovel(novel);
        return result;
    }


}
